﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO.Compression;

/// <summary>
/// 2011.11.30 박승한 압축해제
/// </summary>
public static class CompressionManager
{
    /// <summary>
    /// 압축string -> DataSet/
    /// </summary>
    /// <param name="pByte"></param>
    /// <returns></returns>
    public static DataSet DecompressData(string pByte)
    {
        return DecompressDataSet(Convert.FromBase64String(pByte));
    }

    public static DataSet DecompressDataSet(byte[] bytDs)
    {
        DataSet outDs = new DataSet();

        //스트림으로 가져오기
        MemoryStream inMs = new MemoryStream(bytDs);
        inMs.Seek(0, 0);

        //1. 압축객체 생성- 압축 풀기
        DeflateStream zipStream = new DeflateStream(inMs, CompressionMode.Decompress, true);
        byte[] outByt = ReadFullStream(zipStream);
        zipStream.Flush();
        zipStream.Close();

        //2. 스트림으로 다시변환
        MemoryStream outMs = new MemoryStream(outByt);
        outMs.Seek(0, 0);
        outDs.RemotingFormat = SerializationFormat.Binary;

        //3. 데이터셋으로 Deserialize
        BinaryFormatter bf = new BinaryFormatter();
        outDs = (DataSet)bf.Deserialize(outMs, null);
        return outDs;
    }

    //스트림을 Byte 배열로 변환
    public static byte[] ReadFullStream(Stream stream)
    {
        byte[] buffer = new byte[32768];
        using (MemoryStream ms = new MemoryStream())
        {
            while (true)
            {
                int read = stream.Read(buffer, 0, buffer.Length);
                if (read <= 0)
                    return ms.ToArray();
                ms.Write(buffer, 0, read);
            }
        }
    }
}
